home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 7: Sunsite / Linux Cubed Series 7 - Sunsite Vol 1.iso / system / misc / pclta-1.000 / pclta-1 / hostappl / conio.c < prev    next >
Encoding:
C/C++ Source or Header  |  1996-03-18  |  1.6 KB  |  98 lines

  1. /*
  2.  * conio.c,v 1.0 1996/03/18 14:18:33 miksic Exp
  3.  */
  4.  
  5. /*
  6.  * Implementation of kbhit(), getch() and getche() functions in Linux
  7.  */
  8.  
  9. #include <termios.h>
  10. #include <stdio.h>
  11. #include <unistd.h>
  12. #include <sys/time.h>
  13. #include <errno.h>
  14. #include "conio.h"
  15.  
  16. static struct termios normal_terms;
  17. static int tty;
  18.  
  19. static void go_raw( void );
  20. static void no_echo( void );
  21. static int get_char_wait( void );
  22.  
  23. void
  24. get_normal_terms( void )
  25. {
  26.     tcgetattr( fileno( stdin ), &normal_terms );
  27.     tty = fileno( stdin );
  28. }
  29.  
  30. void
  31. go_normal_terms( void )
  32. {
  33.     tcsetattr( fileno( stdin ), TCSANOW, &normal_terms );
  34. }
  35.  
  36. int
  37. kbhit( void )
  38. {
  39.     fd_set fd;
  40.     struct timeval timeout;
  41.     go_raw();
  42.     FD_ZERO( &fd );
  43.     FD_SET( tty, &fd );
  44.     timeout.tv_sec = timeout.tv_usec = 0;
  45.     while( 0 > select( FD_SETSIZE, &fd, NULL, NULL, &timeout )
  46.            && errno == EINTR );
  47.     go_normal_terms();
  48.     return FD_ISSET( tty, &fd );
  49. }
  50.  
  51. int
  52. getch( void )
  53. {
  54.     go_raw();
  55.     no_echo();
  56.     return get_char_wait();
  57. }
  58.  
  59. int
  60. getche( void )
  61. {
  62.     go_raw();
  63.     return get_char_wait();
  64. }
  65.  
  66. static void
  67. go_raw( void )
  68. {
  69.     struct termios terms;
  70.     tcgetattr( tty, &terms );
  71.     terms.c_lflag &= ~ICANON;
  72.     terms.c_cc[VMIN] = terms.c_cc[VTIME] = 0;
  73.     tcsetattr( tty, TCSANOW, &terms );
  74. }
  75.  
  76. static void
  77. no_echo( void )
  78. {
  79.     struct termios terms;
  80.     tcgetattr( tty, &terms );
  81.     terms.c_lflag &= ~ECHO;
  82.     tcsetattr( tty, TCSANOW, &terms );
  83. }
  84.  
  85. static int
  86. get_char_wait( void )
  87. {
  88.     int ch;
  89.     fd_set fd;
  90.     FD_ZERO( &fd );
  91.     FD_SET( tty, &fd );
  92.     while( 0 > select( FD_SETSIZE, &fd, NULL, NULL, NULL )
  93.            && errno == EINTR );
  94.     ch = getchar();
  95.     go_normal_terms();
  96.     return ch;
  97. }
  98.